import XrHeader from '@/components/XrHeader'
import ListTableHeader from '../components/ListTableHeader'
import {
  jxcFieldQueryListHeadAPI,
  jxcFieldQueryPageListAPI,
  jxcFieldSetFieldStyleAPI,
  jxcFieldAllExportExcelAPI
} from '@/api/jxc/field'

import jxcTypes from '../jxcTypes'
import jxcExamineLib from '../jxcExamineStatus'

import FieldsSet from '../components/fieldsSet'
import AdapterImage from '../components/AdapterImage'
import { isEmpty, isObject, isArray } from '@/utils/types'
import { separator } from '@/filters/vueNumeralFilter/filters'
import { mapGetters } from 'vuex'
import { downloadExcelWithResData } from '@/utils'
import { Loading } from 'element-ui'

/**
 * fieldList Object
 *                width label fixed sortable canVisit
 */
export default {
  components: {
    XrHeader,
    ListTableHeader,
    FieldsSet,
    AdapterImage
  },
  data() {
    return {
      loading: false,
      currentPage: 1, // 当前页码
      pageSizes: [15, 30, 60, 100], // 数据条数选项
      pageSize: 15, // 当前每页数据条数
      total: 0, // 数据总条数

      tableHeight: document.documentElement.clientHeight - 236, // 表格高度
      canResizeTable: true,

      dataList: [], // 表格数据
      fieldList: [], // 表头字段
      otherParams: {}, // 查询附加条件

      selectedList: [], // 选择的列
      controlBtnGroup: [], // 控制按钮
      clickedRow: null, // 被点击的行

      showDetail: false,
      showCreate: false,
      showTransfer: false // 转移
    }
  },
  computed: {
    ...mapGetters(['jxc']),
    /**
     * 类型
     */
    typeObj() {
      return jxcTypes[this.type]
    },
    /**
     * 可以被点击的字段
     * @return {*[]|*}
     */
    canVisitFields() {
      if (!this.fieldList) return []
      return this.fieldList.filter(o => o.canVisit).map(o => o.fieldName || o.field || o.prop)
    },

    /**
     * 新建按钮鉴权
     * @returns {*|boolean}
     */
    canSave() {
      const type = this.type.replace('jxc_', '')
      return this.jxc[type].save || false
    },

    /**
     * 导出按钮鉴权
     * @returns {*|boolean}
     */
    canExport() {
      const type = this.type.replace('jxc_', '')
      return this.jxc[type].excelexport || false
    }
  },
  watch: {
    jxc: {
      handler(val) {
        if (!val || !this.controlBtnGroup || !this.type) return
        const authBtn = ['transfer', 'delete', 'self']
        const type = this.type.replace('jxc_', '')
        // 操作按钮鉴权
        authBtn.forEach(command => {
          const findIndex = this.controlBtnGroup.findIndex(o => o.command === command)
          const auth = val[type] ? (val[type][command] || false) : false
          if (findIndex !== -1 && !auth) {
            this.controlBtnGroup.splice(findIndex, 1)
          }
        })
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    if (this.canResizeTable) {
      this.updateTableHeight()
      window.onresize = () => {
        this.updateTableHeight()
      }
    }
    this.getDataList({}, true)
  },
  methods: {
    /**
     * 获取表头字段和列表数据
     */
    getDataList(params = {}, refresh = false) {
      if (refresh) {
        this.currentPage = 1
      }
      this.otherParams = params
      this.loading = true
      if (refresh) {
        jxcFieldQueryListHeadAPI({
          label: this.typeObj.label
        }).then(res => {
          this.formatField(res.data)
          this._getData(params)
          // this.loading = false
        }).catch(() => {
          this.loading = false
        })
      } else {
        this._getData(params)
      }
    },

    _getData(params) {
      this.loading = true
      jxcFieldQueryPageListAPI({
        page: this.currentPage,
        limit: this.pageSize,
        label: this.typeObj.label,
        ...params
      }).then(res => {
        this.dataList = res.data.list
        this.total = res.data.totalRow
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    examineColor(state) {
      return jxcExamineLib[state].color || ''
    },

    /**
     * 格式化表头字段
     * @param list
     */
    formatField(list) {
      const canVisitFieldsMap = {
        jxc_product: ['productName', 'productPicture'],
        jxc_supplier: ['supplierName'],
        jxc_purchase: ['orderNumber', 'supplierId'],
        jxc_retreat: ['orderNumber', 'supplierId', 'purchaseId'],
        jxc_sale: ['orderNumber', 'customerName'],
        jxc_salereturn: ['orderNumber', 'saleId', 'customerName'],
        jxc_receipt: ['orderNumber'],
        jxc_outbound: ['orderNumber'],
        jxc_collection: ['collectionNo', 'relatedId', 'collectionObject'],
        jxc_payment: ['paymentNo', 'relatedId', 'collectionObject'],
        jxc_allocation: ['allocationNumber'],
        jxc_inventory: ['inventoryNumber']
      }
      const fixedLeftFields = {
        // jxc_product: ['productName', 'productPicture'],
        // jxc_supplier: ['supplierName'],
        // jxc_purchase: ['orderNumber', 'supplierId'],
        // jxc_retreat: ['orderNumber', 'supplierId', 'purchaseId'],
        // jxc_sale: ['orderNumber'],
        // jxc_salereturn: ['orderNumber', 'saleId'],
        // jxc_receipt: ['orderNumber'],
        // jxc_outbound: ['orderNumber'],
        // jxc_collection: ['collectionNo'],
        // jxc_payment: ['paymentNo'],
        // jxc_allocation: ['allocationNumber'],
        // jxc_inventory: ['inventoryNumber']
      }
      list.forEach(field => {
        if (this.type &&
          canVisitFieldsMap[this.type] &&
          canVisitFieldsMap[this.type].includes(field.fieldName)) {
          field.canVisit = true
        }
        if (this.type &&
          fixedLeftFields[this.type] &&
          fixedLeftFields[this.type].includes(field.fieldName)) {
          field.fixed = 'left'
        }
        field.sortable = 'custom'

        if ([
          'supplier_cause',
          'purchase_cause',
          'sale_cause'
        ].includes(field.formType)) {
          field.formatter = function(row, column, cellValue, index) {
            if (cellValue) {
              return cellValue.name
            }
            return '--'
          }
        } else if (field.formType === 'floatnumber') {
          field.formatter = function(row, column, cellValue, index) {
            return separator(cellValue || 0)
          }
        } else if (field.formType === 'file') {
          field.formatter = function(row, column, cellValue, index) {
            if (isArray(cellValue) && !isEmpty(cellValue)) {
              return cellValue.map(o => o.name).join(',')
            }
            return '--'
          }
        } else {
          field.formatter = function(row, column, cellValue, index) {
            if (isObject(cellValue)) {
              return cellValue.name || cellValue || '--'
            }
            return isEmpty(cellValue) ? '--' : cellValue
          }
        }
      })
      this.fieldList = []
      this.$nextTick(() => {
        this.fieldList = list
      })
    },

    getUrl(val) {
      if (!val) return ''
      if (Object.prototype.toString.call(val) === '[object Array]') {
        if (val.length > 0) return val[0]
        return ''
      } else {
        return val
      }
    },

    /**
     * 表格行点击
     * @param row
     * @param column
     */
    handleRowClick(row, column) {
      if (column.type === 'selection') return
      if (this.canVisitFields.includes(column.property)) {
        this.clickedRow = row
        if (this.handleTableClick) {
          this.handleTableClick(row, column.property)
        }
      }
    },

    /**
     * 表格列勾选
     * @param data
     */
    handleSelectionChange(data) {
      this.selectedList = data
    },

    /**
     * 排序
     * @param prop
     * @param order
     */
    handleSort({ prop, order }) {
      // console.log('sort: ', prop, order)
      if (order) {
        // descending 倒序 ascending 正序
        this.otherParams.sortField = prop
        this.otherParams.order = order === 'descending' ? 1 : 2
      } else {
        delete this.otherParams.sortField
        delete this.otherParams.order
      }
      this.getDataList(this.otherParams)
    },

    /**
     * 修改表头列宽
     */
    handleDragend(newWidth, oldWidth, column) {
      if (!this.type || !this.typeObj) return
      jxcFieldSetFieldStyleAPI({
        field: column.property,
        type: this.typeObj.label,
        width: newWidth
      }).then(() => {
      }).catch(() => {
      })
    },

    /**
     * 搜索
     * @param keyword
     */
    handleSearch(keyword) {
      this.otherParams.search = keyword
      this.currentPage = 1
      this.getDataList(this.otherParams)
    },

    /**
     * 场景筛选
     * @param sceneData
     */
    handleSceneChange(sceneData) {
      // console.log('scene data: ', sceneData)
      if (sceneData.id) {
        this.otherParams.sceneId = sceneData.id
        this.getDataList(this.otherParams)
      }
    },

    /**
     * 高级筛选
     */
    handleFilter(filterData = []) {
      if (filterData.length > 0) {
        this.otherParams.searchList = filterData
      } else {
        delete this.otherParams.searchList
      }
      this.updateTableHeight()
      this.getDataList(this.otherParams)
    },

    previewImage(scope, dataIndex = null) {
      let arr = []
      const field = scope.column.property
      if (isEmpty(scope.row[field])) return
      const nowUrl = dataIndex === null ? scope.row[field].url : scope.row[field][dataIndex].url
      this.dataList.forEach((item, i) => {
        if (item[field] instanceof Array) {
          arr = arr.concat(item[field])
        } else {
          arr.push(item[field])
        }
      })
      arr = arr.filter(o => !!o)
      const findIndex = arr.findIndex(o => o.url === nowUrl)
      this.$bus.emit('preview-image-bus', {
        index: findIndex,
        data: arr
      })
    },

    /**
     * 修改每页数据条数
     */
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.getDataList(this.otherParams)
    },

    /**
     * 翻页
     */
    handleCurrentChange(page) {
      this.currentPage = page
      this.getDataList(this.otherParams)
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      return this.canVisitFields.includes(column.property) ? 'can-visit--underline' : ''
    },

    /**
     * 更新表高
     */
    updateTableHeight() {
      const flag = this.otherParams.searchList && this.otherParams.searchList.length > 0
      const offsetHei = document.documentElement.clientHeight
      const removeHeight = flag ? 285 : 235
      // const removeHeight = 235
      this.tableHeight = offsetHei - removeHeight
    },

    /**
     * 刷新
     */
    handleRefresh(data) {
      this.getDataList(this.otherParams, true)
    },

    /**
     * 全部导出
     */
    allExportExcel(request) {
      const allRequest = request || jxcFieldAllExportExcelAPI
      const loading = Loading.service({ fullscreen: true, text: '导出中...' })
      let params = this.otherParams
      if (this.typeObj && this.typeObj.label) {
        params = {
          ...this.otherParams,
          label: this.typeObj.label
        }
      }
      allRequest(params)
        .then(res => {
          downloadExcelWithResData(res)
          loading.close()
        })
        .catch(() => {
          loading.close()
        })
    }
  }
}
